// 表单提交处理
document.addEventListener('DOMContentLoaded', function() {
    const configForm = document.getElementById('config-form');
    
    if (configForm) {
        configForm.addEventListener('submit', function(event) {
            event.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.textContent;
            
            // 禁用按钮并显示加载状态
            submitButton.disabled = true;
            submitButton.textContent = '保存中...';
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    createNotification('success', data.message);
                } else {
                    createNotification('error', '保存失败，请重试');
                }
            })
            .catch(error => {
                createNotification('error', '保存失败，请检查网络连接');
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.textContent = originalButtonText;
            });
        });
    }
    
    // 数据库备份功能
    const backupBtn = document.getElementById('backup-btn');
    if (backupBtn) {
        backupBtn.addEventListener('click', function() {
            const btn = this;
            const originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = '备份中...';
            
            fetch('/admin/backup-database', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    createNotification('success', '数据库备份成功');
                    // 刷新页面以显示最新备份信息
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    createNotification('error', data.message || '备份失败');
                }
            })
            .catch(error => {
                createNotification('error', '备份失败，请重试');
            })
            .finally(() => {
                btn.disabled = false;
                btn.textContent = originalText;
            });
        });
    }
    
    // 自动备份设置功能
    const autoBackupEnabled = document.getElementById('auto_backup_enabled');
    const autoBackupSettings = document.querySelector('.auto_backup_settings');
    const backupFrequency = document.getElementById('backup_frequency');
    const weekdayGroup = document.getElementById('weekday_group');
    const saveBackupConfig = document.getElementById('save_backup_config');
    const testBackupEmail = document.getElementById('test_backup_email');
    
    // 加载当前备份配置
    function loadBackupConfig() {
        fetch('/admin/get-backup-config', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data) {
                autoBackupEnabled.checked = data.enabled || false;
                backupFrequency.value = data.frequency || 'daily';
                document.getElementById('backup_time').value = data.time || '00:00';
                document.getElementById('backup_weekday').value = data.weekday || '0';
                document.getElementById('backup_send_email').checked = data.send_email || false;
                document.getElementById('backup_to_email').value = data.to_email || '';
                
                // 更新UI显示
                updateBackupSettingsVisibility();
                updateWeekdayVisibility();
            }
        })
        .catch(error => {
            console.error('加载备份配置失败:', error);
        });
    }
    
    // 更新备份设置的可见性
    function updateBackupSettingsVisibility() {
        if (autoBackupEnabled.checked) {
            autoBackupSettings.style.display = 'block';
        } else {
            autoBackupSettings.style.display = 'none';
        }
    }
    
    // 更新星期选择的可见性
    function updateWeekdayVisibility() {
        if (backupFrequency.value === 'weekly') {
            weekdayGroup.style.display = 'block';
        } else {
            weekdayGroup.style.display = 'none';
        }
    }
    
    // 保存备份配置
    function saveConfig() {
        const btn = this;
        const originalText = btn.textContent;
        btn.disabled = true;
        btn.textContent = '保存中...';
        
        const configData = {
            enabled: autoBackupEnabled.checked,
            frequency: backupFrequency.value,
            time: document.getElementById('backup_time').value,
            weekday: document.getElementById('backup_weekday').value,
            send_email: document.getElementById('backup_send_email').checked,
            to_email: document.getElementById('backup_to_email').value
        };
        
        fetch('/admin/save-backup-config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'same-origin',
            body: JSON.stringify(configData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                createNotification('success', '备份设置保存成功');
            } else {
                createNotification('error', data.message || '保存失败');
            }
        })
        .catch(error => {
            createNotification('error', '保存失败，请重试');
        })
        .finally(() => {
            btn.disabled = false;
            btn.textContent = originalText;
        });
    }
    
    // 测试发送备份邮件
    function testEmail() {
        const btn = this;
        const originalText = btn.textContent;
        btn.disabled = true;
        btn.textContent = '测试中...';
        
        fetch('/admin/test-backup-email', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                createNotification('success', '测试邮件发送成功');
            } else {
                createNotification('error', data.message || '测试邮件发送失败');
            }
        })
        .catch(error => {
            createNotification('error', '测试邮件发送失败，请重试');
        })
        .finally(() => {
            btn.disabled = false;
            btn.textContent = originalText;
        });
    }
    
    // 添加事件监听器
    if (autoBackupEnabled) {
        autoBackupEnabled.addEventListener('change', updateBackupSettingsVisibility);
    }
    
    if (backupFrequency) {
        backupFrequency.addEventListener('change', updateWeekdayVisibility);
    }
    
    if (saveBackupConfig) {
        saveBackupConfig.addEventListener('click', saveConfig);
    }
    
    if (testBackupEmail) {
        testBackupEmail.addEventListener('click', testEmail);
    }
    
    // 初始加载配置
    loadBackupConfig();
    
    // 删除备份文件功能
    document.querySelectorAll('.delete-backup-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const filename = this.getAttribute('data-filename');
            
            if (confirm(`确定要删除备份文件 "${filename}" 吗？此操作不可恢复。`)) {
                const btn = this;
                const originalText = btn.textContent;
                btn.disabled = true;
                btn.textContent = '删除中...';
                
                fetch(`/admin/delete-backup/${filename}`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    credentials: 'same-origin'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        createNotification('success', '备份文件删除成功');
                        // 刷新页面以更新备份列表
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        createNotification('error', data.message || '删除失败');
                    }
                })
                .catch(error => {
                createNotification('error', '删除失败，请重试');
            })
                .finally(() => {
                    btn.disabled = false;
                    btn.textContent = originalText;
                });
            }
        });
    });
    
    // 添加模态框样式
    const style = document.createElement('style');
    style.textContent = `
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
            width: 90%;
        }
        .modal-content h3 {
            margin-top: 0;
            color: #333;
        }
        .modal-content p {
            color: #666;
            margin-bottom: 15px;
        }
        #countdown {
            font-weight: bold;
            color: #e74c3c;
            font-size: 24px;
        }
        .backup-info {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        .backup-time {
            color: #666;
            font-size: 0.9em;
        }
        .database-actions {
            margin-top: 20px;
        }
    `;
    document.head.appendChild(style);
});

// 通知函数
function createNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 添加样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '4px',
        color: '#fff',
        fontSize: '14px',
        fontWeight: 'bold',
        zIndex: '10000',
        opacity: '0',
        transform: 'translateX(100%)',
        transition: 'opacity 0.3s ease, transform 0.3s ease',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)'
    });
    
    // 根据类型设置背景色
    if (type === 'success') {
        notification.style.backgroundColor = '#52c41a';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#f5222d';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#faad14';
    } else {
        notification.style.backgroundColor = '#1890ff';
    }
    
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        
        // 动画结束后移除元素
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}